package com.bufbomb.datastore;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.*;

@SuppressWarnings("serial")
public class FetchServlet extends HttpServlet {
	@SuppressWarnings("unchecked")
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try
		{
			long id = Long.parseLong(req.getParameter("id"));
			Query query = pm.newQuery(FlashItem.class);
			query.setFilter("id==targetId");
			query.declareParameters("String targetId");
			List<FlashItem> records = (List<FlashItem>) query.execute(id); 
			if (records.isEmpty()) {
				resp.getWriter().println("Empty record.");
			}
			else
			{
				FlashItem su = records.get(records.size() - 1);
				resp.setContentType("application/x-shockwave-flash");
				
				List<DataItem> dataItems = su.getDataItems();
				for(DataItem di : dataItems)
				{
					resp.getOutputStream().write(di.getBlob().getBytes());
				}
				
			}
		}
		finally
		{
			pm.close();
		}
	}
}
